<template>
  <div class="employee-container">
    <div class="header">
      <h2>员工管理</h2>
      <div class="actions">
        <el-button type="primary" icon="Plus" @click="openAddDialog">添加员工</el-button>

        <!-- 查询条件 -->
        <el-input 
          v-model="searchForm.name" 
          placeholder="姓名" 
          style="width: 150px; margin-left: 15px;"
          clearable
        />
        <el-select v-model="searchForm.gender" placeholder="性别" style="width: 120px; margin-left: 10px;">
          <el-option label="男" :value="1" />
          <el-option label="女" :value="2" />
        </el-select>
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="margin-left: 10px;"
        />
        <el-button type="success" icon="Search" @click="fetchEmployees" style="margin-left: 15px;">搜索</el-button>
        <el-button type="danger" icon="Delete" @click="handleBatchDelete" style="margin-left: 15px;">批量删除</el-button>
      </div>
    </div>

    <!-- 员工列表表格 -->
    <el-table :data="employees" border style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="工号" width="80" />
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="gender" label="性别" width="60">
        <template #default="{ row }">
          {{ row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="所属部门" width="140" />
      <el-table-column prop="job" label="职位" width="140">
        <template #default="{ row }">
          {{ positionMap[row.job] || '' }}
        </template>
      </el-table-column>
      <el-table-column prop="entryDate" label="入职时间" width="120" />
      <el-table-column prop="updateTime" label="最后操作时间" width="160" />
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="handlePageChange"
        :page-sizes="[5, 10, 20]"
        @size-change="handleSizeChange"
      />
    </div>

<!-- 编辑员工对话框 -->
<emp-dialog
  v-model="editDialogVisible"
  :employee-id="selectedEmployeeId"
  @success="fetchEmployees"
/>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  getEmployees,
  updateEmployee,
  deleteEmployee,
  getDepartment,
  getAllEmployees,
  addEmployee,
  getEmployeeById,
  indexDepartmentsById
} from '../services/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import EmpDialog from './subviews/EmpDialoag.vue'
components: {
  EmpDialog
}
const loading = ref(false)
const employees = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = ref({
  name: '',
  gender: null,
  dateRange: [],
})

// 分页处理
const handlePageChange = (newPage) => {
  page.value = newPage
  fetchEmployees()
}

const handleSizeChange = (newPageSize) => {
  pageSize.value = newPageSize
  fetchEmployees()
}

// 编辑表单
const editForm = ref({
  id: null,
  username: '',
  password: '',
  name: '',
  gender: 1,
  phone: '',
  entryDate: '',
  deptId: null,
  salary: 0
})

const departments = ref([])
const fetchDepartments = async () => {
  try {
    const response = await getDepartment()
    if (response.data.code === 1) {
      departments.value = response.data.data.rows
    }
  } catch (error) {
    console.error('获取部门失败:', error)
  }
}

onMounted(() => {
  fetchDepartments()
  fetchEmployees()
})

const positionMap = {
  1: '班主任',
  2: '讲师',
  3: '学工主管',
  4: '教研主管',
  5: '咨询师'
}

// 格式化日期为 yyyy-MM-dd
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取员工列表
const fetchEmployees = async () => {
  loading.value = true
  try {
    const [startDate, endDate] = searchForm.value.dateRange || []

    const params = {
      name: searchForm.value.name,
      gender: searchForm.value.gender,
      begin: startDate ? formatDate(startDate) : '',
      end: endDate ? formatDate(endDate) : '',
      page: page.value,
      pageSize: pageSize.value
    }

    const response = await getEmployees(params)

    if (response.data.code === 1) {
      employees.value = response.data.data.rows
      total.value = response.data.data.total
    } else {
      ElMessage.error('获取员工失败')
    }
  } catch (error) {
    console.error('获取员工异常:', error)
    ElMessage.error('网络请求失败')
  } finally {
    loading.value = false
  }
}

// 打开编辑对话框
const editDialogVisible = ref(false)
const selectedEmployeeId = ref(null)

const openEditDialog = (row) => {
  selectedEmployeeId.value = row.id
  editDialogVisible.value = true
}

const openAddDialog = () => {
  selectedEmployeeId.value = null
  editDialogVisible.value = true
}


// 删除员工
const handleDelete = async (id) => {
  ElMessageBox.confirm('确定要删除该员工吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteEmployee([id])
      if (response.data.code === 1) {
        ElMessage.success('删除成功')
        fetchEmployees()
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      console.error('删除员工失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
const multipleSelection = ref([])

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }

  ElMessageBox.confirm('确定要删除选中的员工吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = multipleSelection.value.map(item => item.id)
      const response = await deleteEmployee(ids)
      if (response.data.code === 1) {
        ElMessage.success('批量删除成功')
        fetchEmployees()
      } else {
        ElMessage.error('批量删除失败')
      }
    } catch (error) {
      console.error('批量删除员工失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消批量删除')
  })
}


</script>

<style scoped>
.employee-container {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.actions {
  display: flex;
  align-items: center;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>